package org.yaac.client.activity;

import java.util.List;

import javax.inject.Inject;

import org.yaac.client.YaacCallback;
import org.yaac.client.place.BrowserPlace;
import org.yaac.client.service.CRUDServiceAsync;
import org.yaac.client.ui.BrowserView;
import org.yaac.client.util.ExceptionManager;
import org.yaac.shared.crud.MetaNamespace;
import org.yaac.shared.editor.EntityInfo;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

/**
 * @author Max Zhu (thebbsky@gmail.com)
 *
 */
public class BrowserActivity extends SinglePlaceActivity<BrowserPlace> {

	private final BrowserView view;
	
	private final CRUDServiceAsync service;
	
	private final ExceptionManager exceptionManager;
	
	@Inject
	BrowserActivity(BrowserView view,
			CRUDServiceAsync service, 
			ExceptionManager exceptionManager) {
		super();
		this.view = view;
		this.service = service;
		this.exceptionManager = exceptionManager;
	}

	@Override
	public SinglePlaceActivity<BrowserPlace> withPlace(BrowserPlace place) {
		return this;
	}
	
	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		view.setPresenter(this);
		containerWidget.setWidget(view.asWidget());
		
		if (!view.isMetaDataInit()) {
			// init namespaces
			service.loadMetaData(new AsyncCallback<List<MetaNamespace>>() {
				
				@Override
				public void onSuccess(List<MetaNamespace> metadata) {
					view.onMetadataReady(metadata);
				}
				
				@Override
				public void onFailure(Throwable caught) {
					exceptionManager.handle(caught);
				}
			});	
		}
	}

	public void loadEntities(String kindName, String filter, int start, int length, 
			final YaacCallback<List<EntityInfo>> callback) {
		service.loadEntities(kindName, filter, start, length, new AsyncCallback<List<EntityInfo>>() {
			@Override
			public void onSuccess(List<EntityInfo> result) {
				callback.onSuccess(result);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				callback.onFailure(caught);
			}
		});
	}
}
